#include "Server.h"

GameServer::GameServer(){}
GameServer::~GameServer(){}

int GameServer::initServer(int port){

	//初始化接受连接端口
	int fd =  socket(AF_INET, SOCK_STREAM, 0); 
	struct sockaddr_in bindIP;
	bindIP.sin_family       = AF_INET;
	bindIP.sin_addr.s_addr  = INADDR_ANY;
	bindIP.sin_port         = htons(port);
	bind(fd, (struct sockaddr *)&bindIP, sizeof(bindIP));
	listen(fd, 100);

	listener.setFd(fd);
	listener.ptr = this;
	listener.isListener = true;
	addEvent(listener, NULL);
	
	timer.ptr = this;
	timer.setId(10);
	addTimer(timer, 1, NULL);
	initTables();
	return 0;
}

int GameServer::initTables(){
	for (int i = 1; i<10; i++ )
	{
		Table t(i);
		serverTables.insert( std::pair<int, Table>(i, t) );
	}
	return 0;
}

//net recall
int GameServer::handleOpen(){//一定是自己的ConnInfo
	//printf("a connect in\n");
	int netFd = ::accept(listener.getFd(), NULL, NULL);
	if( netFd < 0 ){
		return -1;
	}
	ConnInfo *newCon = new ConnInfo(netFd);
	newCon->setRecallHandle( this );
	addEvent(*newCon);
	return 0;
}
int GameServer::handleClose( ){//一定是自己的ConnInfo
	return 0;	
}
int GameServer::handleRead(char *buf, unsigned int size, void *args){
	//读取数据
	//printf("a reader in\n");
	//如果是登陆包的话，需要new User，然后进行connInfo回调函数的覆盖
	ConnInfo *pConn = ( ConnInfo * )args;
	if( size < 8 ){
		return 0;
	}
	ESInputPacket input;
	input.Copy(buf, size);
	unsigned short cmd = input.GetCmdType();
	if( true/*用户登录区域*/ ){
		if( cmd == 0x1001 ){
			//用户登录
			int uid = input.ReadInt();
			int tid = input.ReadInt();
			TableMap::iterator iter = serverTables.find(tid);
			if( iter == serverTables.end() ){
				printf("table not found\n");
				return -1;
			}
			printf("user login, uid:%d, tid:%d\n", uid, tid);
			// todo 从存储中获得用户的name, 头像
			string name, icon;
			User *u = new User(uid, name, icon);
			u->setConn(pConn);
			if ( u->UserLogin( tid ) < 0){
				printf("login error\n");
				return -1;
			}
			delEvent(*pConn, false);
			pConn->ptr = u;
			addEvent(*pConn, NULL);
			return 0;
		}
		return -1;
	}else if( true/*admin命令区域*/ ){
		
	}
	return 0;
}
int GameServer::handleWrite(){return 0;}

int GameServer::handleTimeout(int id){
	__printTablesInfo__();
	addTimer(timer, 10, NULL);
	return 0;
}

//test
void GameServer::__printTablesInfo__(){
	TableMap::iterator iter = serverTables.begin();
	for (; iter != serverTables.end(); iter++)
	{
		Table &table = iter->second;
		table.__TableInfo__();
	}
}
//tools
Table *GameServer::getTablePtr(int _t){
	TableMap::iterator iter = serverTables.find(_t);
	if( iter == serverTables.end() ){
		return NULL;
	}
	return &iter->second;
}
